<?php

use Core\AdminController;
use Models\Order_item;
use Models\Refund;

class OrderItemsController extends AdminController
{
	public function save($id)
	{
		$order_item = (new Order_item)->find($id);
		if (!$order_item) {
			return $this->response([], 404);
		}

		$this->load->library('form_validation');
		$this->form_validation->set_rules('price', '价格', 'required|numeric')
			->set_rules('qty', '数量', 'required|integer');
		if ($this->form_validation->run()) {
			$this->db->trans_start();

			$old_qty = $order_item['qty'];
			$old_price = $order_item['price'];
			$old_total = $old_qty*$old_price;

			$order_item['price'] = $this->input->post('price');
			$order_item['qty'] = $this->input->post('qty');
			$order_item->update();
			$order = $order_item->order();

			// 订单金额修改
			$diff = ($old_total - $order_item['price']*$order_item['qty']);
			$order['total'] -= $diff;
			$order->update();

			if ($order['status'] > 0 && $order['status'] < 4) {
				// 已支付的
				$user = $order->user();
				if ($diff > 0) {
					// 总价减少，返余额
					$user['balance'] += $diff* ($order['discount'] ?: 1);
					$user->update();
				} else {
					// todo 增加，是否扣款
					// if ($user['balance'] < $diff) {
					// 	return $this->response(['error_msg' => '用户余额不足'], 422);
					// }
				}

				if ($order_item['qty'] < $old_qty) {
					// 退货
					$refund = new Refund();
					$refund->load([
						'order_id' => $order_item['order_id'],
						'order_item_id' => $order_item['id'],
						'product_id' => $order_item['product_id'],
						'item_id' => $order_item['item_id'],
						'qty' => $old_qty - $order_item['qty'],
						'money' => $diff* ($order['discount'] ?: 1),
						'reason' => '后台订单修改操作',
						'type' => 0,
						'status' => 3,
						'pay_mode' => 0,
						'create_time' => date('Y-m-d H:i:s'),
					]);
					$refund->add();
				}
			}

			$this->db->trans_complete();
			$this->output->enable_profiler();
			return $this->response();
		} else {
			return $this->response($this->form_validation->error_array());
		}
		
	}
}